<template>
  <div :class="['flex', 'justify-between', deviceDetection() && 'flex-wrap']">
    <div :class="[deviceDetection() ? ['w-full', 'mt-2'] : 'w-[calc(100%)]']">
      <el-form
        ref="formRef"
        :inline="true"
        :model="form"
        class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
      >
        <el-form-item label="分组名称：" prop="SearchTerm">
          <el-input
            v-model="form.SearchTerm"
            placeholder="请输入分组名称"
            clearable
            class="w-[180px]!"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            :loading="loading"
            @click="onSearch"
          >
            搜索
          </el-button>
          <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <PureTableBar title="" :columns="columns" @refresh="onSearch">
        <template #buttons>
          <el-button
            type="primary"
            :icon="useRenderIcon(AddFill)"
            @click="openDialog('创建')"
          >
            新增设备分组
          </el-button>
        </template>
        <template v-slot="{ size, dynamicColumns }">
          <div
            v-if="selectedNum > 0"
            v-motion-fade
            class="bg-[var(--el-fill-color-light)] w-full h-[46px] mb-2 pl-4 flex items-center"
          >
            <div class="flex-auto">
              <span
                style="font-size: var(--el-font-size-base)"
                class="text-[rgba(42,46,54,0.5)] dark:text-[rgba(220,220,242,0.5)]"
              >
                已选 {{ selectedNum }} 项
              </span>
              <el-button type="primary" text @click="onSelectionCancel">
                取消选择
              </el-button>
            </div>
            <el-popconfirm title="是否确认删除?" @confirm="onbatchDel">
              <template #reference>
                <el-button type="danger" text class="mr-1!">
                  批量删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
          <pure-table
            ref="tableRef"
            row-key="Id"
            adaptive
            :adaptiveConfig="{ offsetBottom: 108 }"
            align-whole="center"
            table-layout="auto"
            :loading="loading"
            :size="size"
            :data="dataList"
            :columns="dynamicColumns"
            :pagination="{ ...pagination, size }"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            @selection-change="handleSelectionChange"
            @page-size-change="handleSizeChange"
            @page-current-change="handleCurrentChange"
          >
            <template #operation="{ row }">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(EditPen)"
                @click="openDialog('修改', row)"
              >
                编辑
              </el-button>
              <el-dropdown>
                <el-button
                  class="ml-3! mt-[2px]!"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon('ep:more')"
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <el-button
                        class="reset-margin"
                        link
                        type="danger"
                        :size="size"
                        :icon="useRenderIcon(Delete)"
                        @click.stop="handleDelete(row)"
                      >
                        删除
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button
                        link
                        type="primary"
                        :size="size"
                        @click="handleViewDevices(row)"
                      >
                        查看设备
                      </el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template #status="{ row }">
              <span
                :class="{
                  'bg-green-500 text-white px-2 py-1 rounded':
                    row.status === '激活',
                  'bg-red-500 text-white px-2 py-1 rounded':
                    row.status === '停用'
                }"
              >
                {{ row.status }}
              </span>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>
  </div>
  <!-- 设备列表对话框 -->
  <el-dialog
    v-model="deviceDialogVisible"
    :title="`${currentGroupName} - 设备列表`"
    width="50%"
    :before-close="handleDeviceDialogClose"
  >
    <div v-if="deviceDialogVisible" class="device-list-container">
      <div v-if="deviceLoading" class="text-center py-4">
        <el-icon><Loading /></el-icon>
        <span class="ml-2">加载中...</span>
      </div>
      <el-table
        v-loading="deviceLoading"
        :data="currentGroupDevices"
        style="width: 100%"
      >
        <el-table-column prop="Name" label="设备名称" min-width="150" />
        <el-table-column prop="Code" label="编号" min-width="120" />
        <el-table-column prop="Type" label="类型" min-width="100" />
        <el-table-column prop="Params" label="参数" min-width="200" />
      </el-table>
      <div
        v-if="!deviceLoading && currentGroupDevices.length === 0"
        class="text-center py-8 text-gray-500"
      >
        暂无数据
      </div>
      <div
        v-if="!deviceLoading && currentGroupDevices.length > 0"
        class="text-right mt-2 text-gray-500"
      >
        共 {{ currentGroupDevices.length }} 台设备
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deviceDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from "vue";
import { PureTable } from "@pureadmin/table";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import Search from "~icons/ep/search";
import { useDeviceGroupTable } from "../componentsUtils/useDeviceGroupTable";
import { message } from "@/utils/message";
import { Loading } from "@element-plus/icons-vue";
// 定义props
const props = defineProps<{
  lesseeId: number;
  dealerId: number;
  tenantName: string;
  dealerName: string;
}>();

const tableRef = ref();
const formRef = ref();
const deviceDialogVisible = ref(false);
const currentGroupName = ref("");
const currentGroupDevices = ref([]);
const deviceLoading = ref(false);

const {
  form,
  loading,
  columns,
  dataList,
  selectedNum,
  pagination,
  deviceDetection,
  onSearch,
  resetForm,
  onbatchDel,
  openDialog,
  handleDelete,
  handleSizeChange,
  onSelectionCancel,
  handleCurrentChange,
  handleSelectionChange,
  fetchDevicesByGroup
} = useDeviceGroupTable(
  tableRef,
  props.lesseeId,
  props.dealerId,
  props.tenantName,
  props.dealerName
);

// 处理查看设备
const handleViewDevices = row => {
  currentGroupName.value = row.Name;
  deviceDialogVisible.value = true; // 先显示对话框
  deviceLoading.value = true;
  fetchDevicesByGroup(row.Id)
    .then(devices => {
      // 确保设备数据是数组
      if (Array.isArray(devices)) {
        currentGroupDevices.value = devices;
      } else {
        currentGroupDevices.value = [];
      }
      deviceLoading.value = false;
    })
    .catch(() => {
      message("获取设备列表失败", { type: "error" });
      deviceLoading.value = false;
    });
};

// 处理设备对话框关闭
const handleDeviceDialogClose = () => {
  deviceDialogVisible.value = false;
};
</script>

<style scoped>
/* 调整操作列按钮样式 */
:deep(.el-table__cell) {
  .flex.space-x-2 {
    display: flex;
    gap: 8px;
  }
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.device-list-container {
  max-height: 400px;
  overflow-y: auto;
}
</style>
